package com.zxl.always.on.display.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zxl.always.on.display.R;

/**
 * Created by Administrator on 2018/2/26.
 */

public class SettingItem extends LinearLayout implements View.OnClickListener {

    private String title, summary;

    private boolean isShowUnderline, isShowSwitch, switchStatus;

    private SwitchCompat mSwitch;

    private TextView titleView, summaryView;

    private OnClickListener mOnItemClickListener;

    public SettingItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingItem);
        title = typedArray.getString(R.styleable.SettingItem_text);
        summary = typedArray.getString(R.styleable.SettingItem_summary);
        isShowUnderline = typedArray.hasValue(R.styleable.SettingItem_underline);
        isShowSwitch = typedArray.hasValue(R.styleable.SettingItem_checked);
        if (isShowSwitch) {
            switchStatus = typedArray.getBoolean(R.styleable.SettingItem_checked, false);
        }
        typedArray.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        LayoutInflater.from(getContext()).inflate(R.layout.widget_settings_item, this, true);
        findViewById(R.id.view_item).setOnClickListener(this);
        findViewById(R.id.bottom_divider).setVisibility(isShowUnderline ? VISIBLE : GONE);

        mSwitch = findViewById(R.id.set_all_day_switch);
        mSwitch.setVisibility(isShowSwitch ? VISIBLE : GONE);
        mSwitch.setChecked(switchStatus);

        titleView = findViewById(R.id.item);
        if (!TextUtils.isEmpty(title)) {
            titleView.setText(title);
        }

        summaryView = findViewById(R.id.summary);
        setSummary(summary);
    }

    public void setOnItemClickListener(OnClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }

    public void setSummary(String summary) {
        if (TextUtils.isEmpty(summary)) {
            summaryView.setVisibility(View.GONE);
        } else {
            summaryView.setVisibility(View.VISIBLE);
            summaryView.setText(summary);
        }
    }

    public void setChecked(boolean isChecked) {
        mSwitch.setChecked(isChecked);
    }

    public void toggle() {
        mSwitch.setChecked(!mSwitch.isChecked());
    }

    public boolean isChecked() {
        return mSwitch.isChecked();
    }

    @Override
    public void onClick(View v) {
        if (null != mOnItemClickListener) {
            mOnItemClickListener.onClick(this);
        }
    }

}
